#include "StdAfx.h"
#include "Overlapper.h"
#include "Sample.h"

Overlapper::Overlapper(int overlapLength)
{
	this->overlapLength = overlapLength;
	lastSample.resize(overlapLength, 0);
}

Overlapper::~Overlapper(void)
{
}

void Overlapper::NextOverlap(Sample* sample)
{
	
	int oldLength = sample->GetLength();
	short* incomingData = sample->GetData();

	int newLength = sample->GetLength()-overlapLength;
	Sample newSample(newLength);
	short* newData = newSample.GetData();
	int outputIdx=0;
	for(; outputIdx<overlapLength; outputIdx++)
	{
		//merge together last sample and current one
		double lastIntensity = ((double)(overlapLength-outputIdx))/(double)overlapLength;
		double nextIntensity = (double)outputIdx/(double)overlapLength;
		int s = (int)((lastSample[outputIdx]*lastIntensity) + (incomingData[outputIdx]*nextIntensity));
		if(s>SHORT_MAX || s<SHORT_MIN) 
		{
			int x = 0;
			s = 1/x;//program must have errors for this to be possible;
		}
		lastSample[outputIdx] = incomingData[outputIdx];
		newData[outputIdx] = (short)s;
	}
	for(; outputIdx<newLength; outputIdx++)
	{
		newData[outputIdx] = incomingData[outputIdx];		
	}
	sample->CopyFrom(&newSample, NULL);
}